//
//  SAPlayViewController.m
//  GameFrame
//
//  Created by Hiroshi Nomura on 2014/05/24.
//  Copyright (c) 2014年 Hiroshi Nomura. All rights reserved.
//

#import "SAPlayViewController.h"

#import "SAPlayAppManager.h"
#import "SAAppGlobalConfig.h"
#import "SAAppCurrentStatus.h"

@interface SAPlayViewController ()

-(void)startLinkDisplay;
-(void)stopLinkDisplay;

@property (nonatomic, assign)CADisplayLink* displayLink;
@property (nonatomic, assign)BOOL isLinkDisplay;

@end


@implementation SAPlayViewController

@synthesize appManager, appConfig;
@synthesize isLinkDisplay;

-(void)startLinkDisplay
{
    if (!isLinkDisplay) {
        CADisplayLink* mainDisplayLink = [[UIScreen mainScreen]
                                       displayLinkWithTarget:self selector:@selector(update)];
        [mainDisplayLink setFrameInterval:self.appConfig.updateInterval];
        [mainDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        self.displayLink = mainDisplayLink;

        isLinkDisplay = YES;
    }
}

-(void)stopLinkDisplay
{
    if (isLinkDisplay)
    {
        [self.displayLink invalidate];
        self.displayLink = nil;
        isLinkDisplay = NO;
    }
}

/*- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}*/

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    [appManager setupApp:appConfig.selectedStage];
    [appManager start];
    
    self.isLinkDisplay = NO;
    [self startLinkDisplay];
}

- (void)viewDidUnLoad
{
	// Relase resource objects before app exits the view.
    [appManager exit];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)update
{
    //Update Current Status View
    SAAppCurrentStatus* status = appManager.status;
    
    CFTimeInterval nextUpdateTIme =  self.displayLink.timestamp;
    
    [appManager render];
    
    [appManager update];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@"touuchStart");
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@"touuchMove");
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@"touuchEnd");
    //[appManager handleConsoleEvent];
}

@end
